/*
 * @Author: chengsl
 * @Date: 2022-11-03 14:54:17
 * @LastEditors: chengsl
 * @LastEditTime: 2022-12-01 16:44:18
 * @Description: 请求地址分配
 */

var { urlParamsToObj, errorToString } = require('./utils')
var { daoObj } = require('./dao')
var { Logger } = require('./log/logger')
const logger = new Logger({fileName:'router.js'})
async function route(pathname, params) {
  return new Promise((resolve, reject) => {
    if (pathname == '/favicon.ico') {
      return reject('[ERROR] ' + '非法请求')
    }
    try {
      let option = {}
      option.params = params //urlParamsToObj(query)
      logger.info(`请求路径：${pathname},参数为：${JSON.stringify(params)}   ---- router`)
      option.params.tableName = option.params.tableName || 'tb_user' // 没传表名默认查 tb_user 表
      let currentMethod = ''
      switch (pathname) {
        case '/query':
          option.optionName = '查询'
          currentMethod = 'select'
          break
        case '/add':
          option.optionName = '增加'
          currentMethod = 'add'
          break
        case '/delete':
          option.optionName = '删除'
          currentMethod = 'del'
          break
        case '/update':
          option.optionName = '更新'
          currentMethod = 'upd'
          break
        default:
          option.optionName = '其他'
          break
      }
      daoObj[currentMethod](option.params)
        .then(res => {
          option.result = res
          resolve(option)
        })
        .catch(err => {
          reject('[ERROR] ' + err)
        })
    } catch (error) {
      reject('[ERROR] ' + errorToString(error))
    }
  })
}

module.exports = {
  route
}
